﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace MuaBanLike.com
{
    /// <summary>
    /// Interaction logic for PopupWindow.xaml
    /// </summary>
    public partial class PopupWindow : Window
    {

        public MainWindow mainWnd = null;

        BackgroundWorker threadTimer = null;
        BackgroundWorker threadDetection = null;

        bool m_bFinish;
        public string slink;
        public PopupWindow()
        {
            InitializeComponent();                       
            this.ShowInTaskbar = false;
            m_bFinish = false;
        }


        [DllImport("KERNEL32.DLL", EntryPoint = "SetProcessWorkingSetSize", SetLastError = true, CallingConvention = CallingConvention.StdCall)]
        internal static extern bool SetProcessWorkingSetSize(IntPtr pProcess, int dwMinimumWorkingSetSize, int dwMaximumWorkingSetSize);

        [DllImport("KERNEL32.DLL", EntryPoint = "GetCurrentProcess", SetLastError = true, CallingConvention = CallingConvention.StdCall)]
        internal static extern IntPtr GetCurrentProcess();


        void freeMemory()
        {
            IntPtr pHandle = GetCurrentProcess();
            SetProcessWorkingSetSize(pHandle, -1, -1);
        }
        public void disposeWebControl()
        {
            if (threadTimer != null)
            {
                threadTimer.CancelAsync();
                threadTimer = null;
            }
            this.popupBrowser.Dispose();          
        }

        DateTime startTime;
        void delaySomeMinute()
        {
            startTime = DateTime.Now;
            threadTimer = new BackgroundWorker();

            threadTimer.DoWork += delay5second;
            threadTimer.RunWorkerCompleted += closePopup;
            threadTimer.WorkerReportsProgress = true;
            threadTimer.WorkerSupportsCancellation = true;
            threadTimer.RunWorkerAsync();
        }

        private void delay5second(Object sender, DoWorkEventArgs e)
        {
            Thread.Sleep(5000);
            //while (true)
            //{

            //    TimeSpan time = DateTime.Now - startTime;

            //    if (time.Seconds > 5)
            //    {
            //        break;
            //    }

            //}
        }
        private void closePopup(Object sender, RunWorkerCompletedEventArgs e)
        {
            if (threadTimer != null && !threadTimer.IsBusy)
            {
                threadTimer.CancelAsync();
                threadTimer = null;
                //re-check
                if (mainWnd.m_serviceActive == ServiceAction.LIKE)
                {
                    var doc = (mshtml.HTMLDocument)popupBrowser.Document;                    
                    var lableTag = doc.getElementById("timelineHeadlineLikeButton");

                    if (lableTag != null)
                    {
                        foreach (var linkLike in lableTag.children)
                        {
                            mshtml.HTMLInputElement likedBtn = linkLike as mshtml.HTMLInputElement;
                            if (likedBtn != null)
                            {                               
                                likedBtn.click();                                
                            }
                        }
                    }
                    
                }
                else if (mainWnd.m_serviceActive == ServiceAction.FOLLOW)
                {
                    var doc = (mshtml.HTMLDocument)popupBrowser.Document;
                    
                    var lspanTag = doc.getElementById("timeline_following_swap_button");

                    if (lspanTag != null && lspanTag.children != null)
                    {
                        mshtml.HTMLAnchorElement follow = lspanTag.children[0] as mshtml.HTMLAnchorElement;                       
                        if (follow != null)
                        {
                            if (!follow.className.Contains("hidden_elem"))
                            {
                                follow.click();
                            }
                            
                        }
                    }
                }
                this.popupBrowser.Dispose();

                if (mainWnd != null)
                    mainWnd.onClosePopup();
            }
        }
       
        private void onClosing(object sender, EventArgs e)
        {
            if (!m_bFinish)            
                mainWnd.m_bCanSkip = false;            
            else
                mainWnd.m_bCanSkip = true;
        }
 
        void startDetect()
        {
            if (mainWnd != null)
            {
                startTime = DateTime.Now;
                threadDetection = new BackgroundWorker();

                threadDetection.DoWork += (sender, e) => { Thread.Sleep(1000); };
                if (mainWnd.m_serviceActive == ServiceAction.LIKE)
                    threadDetection.RunWorkerCompleted += onDetectLike;
                else if (mainWnd.m_serviceActive == ServiceAction.FOLLOW)
                    threadDetection.RunWorkerCompleted += onDetectFollow;
                threadDetection.WorkerReportsProgress = true;
                threadDetection.WorkerSupportsCancellation = true;
                
                threadDetection.RunWorkerAsync();
            }

        }

        private int m_nRetry = 0;
        private void onDetectLike(Object sender, RunWorkerCompletedEventArgs e)
        {
            if (threadDetection != null && !threadDetection.IsBusy)
            {
                //freeMemory();
                threadDetection.CancelAsync();
                threadDetection = null;
                var doc = (mshtml.HTMLDocument)popupBrowser.Document;

                if (doc == null)
                    startDetect();                
                //u_0_1t (liked) , u_0_1u (like)
                var lableTag = doc.getElementById("timelineHeadlineLikeButton");

                if (lableTag != null)
                {
                    foreach (var linkLike in lableTag.children)
                    {
                        mshtml.HTMLInputElement likedBtn = linkLike as mshtml.HTMLInputElement;
                        if (likedBtn != null)
                        {                            
                            likedBtn.click();
                            m_bFinish = true;
                            delaySomeMinute();
                        }
                    }
                }
                else
                {
                    var likedBtn = doc.getElementById("u_0_1t");
                    if (likedBtn != null)
                    {                        
                        this.popupBrowser.Dispose();

                        if (mainWnd != null)
                        {
                            m_bFinish = true;
                            mainWnd.m_bCanSkip = true;
                            mainWnd.onClosePopup();
                        }
                    }
                    else
                    {                      
                        if (m_nRetry < 8)
                        {
                            m_nRetry++;
                            startDetect();
                        }
                        else
                        {
                            m_nRetry = 0;
                            this.popupBrowser.Dispose();

                            if (mainWnd != null)
                                mainWnd.onClosePopup();

                        }
                    }
                }
            }
        }
        private void onDetectFollow(Object sender, RunWorkerCompletedEventArgs e)
        {
            if (threadDetection != null && !threadDetection.IsBusy)
            {
                threadDetection.CancelAsync();
                threadDetection = null;
                var doc = (mshtml.HTMLDocument)popupBrowser.Document;
                if (doc == null)
                    startDetect();
                //u_0_1t (liked) , u_0_1u (like)
                var lspanTag = doc.getElementById("timeline_following_swap_button");

                if (lspanTag != null && lspanTag.children != null)
                {
                    mshtml.HTMLAnchorElement follow = lspanTag.children[0] as mshtml.HTMLAnchorElement;
                    mshtml.HTMLAnchorElement unfollow = lspanTag.children[1] as mshtml.HTMLAnchorElement;
                    if (follow != null && unfollow != null)
                    {
                        if (follow.className.Contains("hidden_elem"))
                        {                           
                            this.popupBrowser.Dispose();

                            if (mainWnd != null)
                                mainWnd.onClosePopup();
                        }
                        else
                        {                            
                            follow.click();
                            m_bFinish = true;
                            delaySomeMinute();
                        }
                    }
                }
                else
                {
                    TimeSpan time = DateTime.Now - startTime;

                    if (m_nRetry < 8)
                    {
                        m_nRetry++;
                        startDetect();
                    }
                    else
                    {
                        m_nRetry = 0;
                        this.popupBrowser.Dispose();

                        if (mainWnd != null)
                            mainWnd.onClosePopup();
                    }
                }

            }
        }

        private void OnNavigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            if (e.Uri.ToString() == slink)
            {               
                startDetect();
            }
            else if(e.Uri.ToString() != "about:blank")
            {
                mainWnd.showPopup();
            }
            
        }       
    }
}
